package com.androidsandsheep.androidto.widget;

import java.text.SimpleDateFormat;

import java.util.Random;

//import com.random.heimdallr.R;

import android.content.res.Resources;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

public class BasicWidgetProvider extends AppWidgetProvider {
	
	static final String TAG = "BasicWidgetProvider";
	
	final static String REFRESH = "refresh";
	
	final static int UPDATE_RATE = 10000; //every 30 seconds
	
private static String[] myString;
   private static final Random rgenerator = new Random();
	
	/* Override onReceive in order to accommodate the new Refresh intent 
	 * Otherwise it's handled by the AppWidgetProvider class */
	@Override
	public void onReceive(Context context, Intent intent) {
		if (REFRESH.equals(intent.getAction())) {
			Log.d(TAG, "onReceive() with REFRESH intent");
			context.startService(new Intent(context, UpdateService.class));
			Toast.makeText(context, "onReceive() with REFRESH intent", Toast.LENGTH_SHORT).show();
		}else{
			super.onReceive(context, intent);
		}
	}
	
	/* Called when the widget is created for the first time */
	@Override
	public void onEnabled( Context context ) {
		super.onEnabled(context);
		// TODO This is where you would set up any databases
		Toast.makeText(context, "onEnabled()", Toast.LENGTH_SHORT).show();
	}
	
	/* Called when a widget is updated. This is based on the updatePeriodMillis definition in the AppWidgetProviderInfo (xml/appwidget.xml) */
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		Log.d(TAG, "onUpdate()");
		 
		// update each widget that belongs to this provider individually by setting an alarm
		// because we're setting an alarm, onUpdate is really only called when a new widget is added, or the phone restarts
		final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];
            setAlarm(context, appWidgetId, UPDATE_RATE);
        }
        
        Toast.makeText(context, "onUpdate()", Toast.LENGTH_SHORT).show();
	}
		
	public static void setAlarm(Context context, int appWidgetId, int updateRate) {
		// To prevent any ANR timeouts, we perform the update in an intent service
	    PendingIntent pendingIntent = createUpdatePendingIntent(context,REFRESH,appWidgetId);
	    AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	    //and then have the alarm wake up the system to do updates
	    alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), updateRate, pendingIntent);
	}
	
	public static PendingIntent createUpdatePendingIntent(Context context, String command, int appWidgetId) {
	    Intent active = new Intent(context,UpdateService.class);
	    active.setAction(command);
	    active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
	    Uri data = Uri.withAppendedPath(Uri.parse("basicwidget://widget/id/#"+command+appWidgetId), String.valueOf(appWidgetId)); //make unique uri to avoid collisions
	    active.setData(data);
	    PendingIntent pendingIntent = PendingIntent.getService(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT);
	    return pendingIntent;
	}
	
	public static void clearAlarm(Context context, int appWidgetId) {
		PendingIntent newPending = createUpdatePendingIntent(context,REFRESH,appWidgetId);
		AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarms.cancel(newPending);
	}
	
	//inner class for updating remote views
	public static class UpdateService extends IntentService {
		
		public UpdateService(){
			super("BasicWidgetProvider$UpdateService");
		}
		
		@Override
	    public void onHandleIntent(Intent intent) {
			Log.d(TAG, "onHandleIntent()");
	        ComponentName widget = new ComponentName( this, BasicWidgetProvider.class );
	        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
	        appWidgetManager.updateAppWidget(widget, buildUpdate(this, intent));
	    }

		private RemoteViews buildUpdate(Context context, Intent intent) {
			Log.d(TAG, "buildUpdate(): " + this);
			
			RemoteViews views = new RemoteViews( context.getPackageName(), R.layout.widget );
			
			//generaljuk a veletlen szoveget
		//	private String[] myString;
		//    private static final Random rgenerator = new Random();
			 Resources res = getResources();

		        myString = res.getStringArray(R.array.myArray); 

		        String q = myString[rgenerator.nextInt(myString.length)];

		      // TextView tv = (TextView) findViewById(R.id.text1);
		       // tv.setText(q);
			
			
			// format and display current time
			SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, MMM dd ':' hh:mm a");
			String formattedTime = dateFormatter.format( System.currentTimeMillis() );
	        views.setTextViewText(R.id.current_time, context.getText(R.string.current_time) + formattedTime + "\n\n"+ q );

	        Intent refreshIntent = new Intent( this, BasicWidgetProvider.class );
	        refreshIntent.setAction(REFRESH);
	        //PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, 0);
	       // views.setOnClickPendingIntent( R.id.refresh, pendingIntent);
	        
	        
			return views;
		}

	}
	
	/* Called when the a widget is deleted */
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);
	    for (int appWidgetId : appWidgetIds) {      
	    	clearAlarm(context, appWidgetId);
	    }
        Toast.makeText(context, "onDeleted()", Toast.LENGTH_SHORT).show();
	}
	
	/* Called when the last widget is deleted */
	@Override
	public void onDisabled( Context context ) {
		Log.d(TAG, "onDisabled()");
		super.onDisabled(context);
		context.stopService(new Intent(context,UpdateService.class));
		// TODO This is where you would delete any databases created in onEnabled
        Toast.makeText(context, "onDisabled()", Toast.LENGTH_SHORT).show();
	}

}
